import * as vscode from 'vscode';
import { MarkdownExplorer } from './views/markdownExplorer';
import { DraftManager } from './services/draftManager';

export async function activate(context: vscode.ExtensionContext) {
    // 确保有工作区
    if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
        vscode.window.showInformationMessage('Please open a workspace to use MD to WX Explorer');
        return;
    }

    const workspaceRoot = vscode.workspace.workspaceFolders[0].uri;

    // 检查是否存在 cache_db.version 文件
    const dbVersionFile = vscode.Uri.joinPath(workspaceRoot, 'cache_db.version');
    try {
        const stat = await vscode.workspace.fs.stat(dbVersionFile);
        if (!stat) {
            return; // 如果文件不存在，不激活插件
        }
    } catch {
        return; // 如果发生错误（文件不存在），不激活插件
    }

    const workspaceRootPath = workspaceRoot.fsPath;
    const draftManager = new DraftManager(context);
    const markdownExplorer = new MarkdownExplorer(workspaceRootPath, draftManager);

    // 将 draftManager 添加到订阅列表以确保正确释放资源
    context.subscriptions.push(draftManager);

    // 注册视图
    const treeView = vscode.window.createTreeView('markdownExplorer', {
        treeDataProvider: markdownExplorer.getTreeDataProvider(),
        showCollapseAll: true
    });

    // 激活时立即刷新视图加载文件
    markdownExplorer.refresh();

    // 注册命令
    const refreshCommand = vscode.commands.registerCommand('markdownExplorer.refresh', () => {
        markdownExplorer.refresh();
    });

    const openFileCommand = vscode.commands.registerCommand('markdownExplorer.openFile', (uri: vscode.Uri) => {
        vscode.workspace.openTextDocument(uri).then(doc => {
            vscode.window.showTextDocument(doc);
        });
    });

    // 添加到订阅列表
    context.subscriptions.push(
        treeView,
        refreshCommand,
        openFileCommand
    );
}

export function deactivate() {
    // 资源清理会通过 disposables 自动处理
    // DraftManager 的 dispose 方法会被自动调用
}